<template>
    <div class="blog-comment-container">
        <MessageAreaIndex
            title="评论列表"
            :sub-title="`(${data!.total})`"  
            :list="data!.rows"  
            :is-list-loading="isLoadding"
            @submit="handleSubmit"
        ></MessageAreaIndex>
    </div>
</template>
<script setup lang='ts'>
import MessageAreaIndex from '~@/components/MessageArea/MessageAreaIndex.vue';
import { getComments,postComment } from '~@/api/blog';
import { computed, onBeforeUnmount, onMounted, ref } from 'vue';
import { TypeApiCommentI, TypeApiCommentPageI } from '~@/api/apiTypes';
import { useRoute } from 'vue-router';
import { $bus } from '~@/bus/busIndex';
import { throttle } from '~@/untils/NslUtils';

const data=ref<TypeApiCommentPageI>({total:0,rows:[]});
const page=ref(1);
const limit=ref(10);

const route=useRoute();
const isLoadding=ref(false);

onMounted(async ()=>{
    isLoadding.value=true;
    data.value=await getComments(new Number(route.params.id).valueOf(),page.value,limit.value);
    isLoadding.value=false;
});

onMounted(()=>{
    $bus.on('mainScroll',handleScroll);
})

onBeforeUnmount(()=>{
    $bus.off('mainScroll',handleScroll)
})


const handleScroll=throttle((dom : HTMLElement | undefined)=>{
    if(dom && !isLoadding.value){
        const height=Math.abs(dom.scrollTop+dom.clientHeight-dom.scrollHeight);
        if(height<100){
            fetchMore();
        }
    }
},200,true)

const hasMoreCom=computed(()=>{
    return data.value.rows.length<data.value.total;
})

const fetchMore=async ()=>{
    if(hasMoreCom.value){
        isLoadding.value=true;
        page.value++;
        const moreData=await getComments(new Number(route.params.id).valueOf(),page.value,limit.value);

        data.value.rows=data.value.rows.concat(moreData.rows);
        data.value.total=data.value.total;
        isLoadding.value=false;
    }
}

const handleSubmit=async (formData:TypeApiCommentI,callback:Function)=>{
    isLoadding.value=true;
    const resp=await postComment({
        blogId:new Number(route.params.id).valueOf(),
        ...formData
    });
    
    data.value?.rows.unshift(resp);
    data.value!.total++;
    isLoadding.value=false;
    callback('评论成功');

}
</script>
<style lang='less' scoped>
.blog-comment-container {
    margin: 30px 0;
}  
</style>